package org.mtmi.ui.controls.edits;

import java.util.Collection;

import org.mtmi.ui.IMG;
import org.mtmi.ui.actions.RetargetableAction;
import org.mtmi.ui.controls.ValueTransformer;
import org.mtmi.ui.controls.curve.CurveValueTransformer;
import org.mtmi.ui.controls.curve.EditCurvePopup;
import org.mtmi.ui.controls.curve.IValueTransformer;
import org.mtmi.ui.controls.listeners.PopupListener;
import org.mtmi.ui.drawables.IDrawable;

/**
 * Action to change or edit curve associated to a {@link ValueTransformer}
 */
public class ValueTransformerEditCurveAction extends RetargetableAction
{

	public ValueTransformerEditCurveAction() {
		super( PUSH );
	}

	@Override
	public boolean isTargetHandled(Object c) {
		return c instanceof ValueTransformer;
//TODO: can share ? popup require at least a curve		return isInstanceOfOrCollectionOfInstanceOf( c, ValueTransformer.class );
	}

	@Override
	public IDrawable getImage() {
		return IMG.GetD( IMG.I_MIDI_VALUE );
	}

	@Override
	public boolean isEnabled() {
		return target!=null;
	}
	
	@Override
	public void run() {
		Object t = getTarget();
		if( t instanceof ValueTransformer ) {
			run( (ValueTransformer)t );
		} else {
//TODO: see isTargetHandled()			
			for( Object o : (Collection<?>)t ) {
				run( (ValueTransformer)o );
			}
		}
	}
	
	private void run( final ValueTransformer vt ) 
	{
		final EditCurvePopup popup = new EditCurvePopup( vt.getScene(), 0 );
		
		IValueTransformer ivt = vt.getValueTransformer();
		if( ivt instanceof CurveValueTransformer ) {
			popup.setCurve( (CurveValueTransformer)ivt );
		}
		
		popup.addResponseListener( new PopupListener() {
			@Override
			public void popupButtonSelected(int id) {
				vt.setValueTransformer( popup.getCurve() );
			}
		});
	}

}
